package org.shoukaiseki.app.interceptor.interceptor;

import org.shoukaiseki.app.interceptor.annotation.Anon;
import org.shoukaiseki.app.interceptor.constant.AppAccessInterceptorConstants;
import org.shoukaiseki.app.interceptor.logger.AppAccessLoggers;
import org.shoukaiseki.common.logger.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * App访问拦截器
 * org.shoukaiseki.app.interceptor.AppAccessInterceptor
 * <br>
 *
 * @author shoukaiseki ブログ http://www.shoukaiseki.top/<br> E-メール jiang28555@Gmail.com<br>
 * @date 2020-12-09 09:53:21<br>
 */
@Component
public class AppAccessInterceptor  extends HandlerInterceptorAdapter {


    public static final Logger logger=AppAccessLoggers.APP_ACCESS_LOGGER;

    /**
     * 未登录验证跳转页面
     */
    @Value("${sks.app.access.interceptor.nologintips}")
    private String noLoginTips="/login";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        Object obj = session.getAttribute(AppAccessInterceptorConstants.APP_USER_SESSION_ATTRNAM);
        if(obj==null){
            if (handler instanceof HandlerMethod)
            {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                if(handlerMethod.hasMethodAnnotation(Anon.class)){
                    return super.preHandle(request, response, handler);
                }else{
                }
            }
            else
            {
                return super.preHandle(request, response, handler);
            }
        }else{
            return super.preHandle(request, response, handler);
        }

        response.sendRedirect(noLoginTips);
        return false;
    }
}